<template>
  <div class="chainStoreSearch">
    <c-title :hide="false" :text="`搜索`" id="soso" ref="soso"></c-title>
    <div class="searchInp">
      <van-search @focus="hidebox" @blur="searchBlur" v-model="keyWork" placeholder="请输入搜索关键词" shape="round" @search="getData" />
    </div>
    <div v-show="pageReload"></div>
    <transition name="fateOut" v-on:enter="fateOutEnter" v-on:after-leave="fateOutLeave">
      <sarchHistory v-show="showHistory" :storageName="storageName" ref="searchHistory" @clickTag="serachTag" @popTag="getSosoHeight"></sarchHistory>
    </transition>
    <div class="list">
      <div class="lis" v-for="(item, index) in info" :key="index" @click="childGoodTap(item.id)">
        <div class="left">
          <img :src="item.thumb" alt="" />
        </div>
        <div class="right">
          <div class="title">{{ item.title }}</div>
          <div class="price">¥{{ item.price }}</div>
        </div>
      </div>
    </div>
    <yzGoodsPopup
      @updateChild="getCart"
      :store_id="store_id"
      :cardata="carts"
      :goodsCartsTotal="goodsCartsTotal"
      :roundShow="true"
      :_goodsInfo="_goodsInfo"
      :showgp="showGood"
      v-if="showGood"
      :goodsInfo="activeGood"
      :themeColor="themeColor"
      :cartsNum="cartsNum"
      :cartsTotal="cartsTotal"
      @onEmit="yzGoodsPopupClose"
      @toOrder="goodsOrder"
      @cartUpdate="getCart"
      :tag="'search'"
    />
  </div>
</template>
<script>
import sarchHistory from "components/searchHistory";
import { scrollMixin } from "utils/mixin";
import yzGoodsPopup from "./components/yz_goodsPopup.vue";
export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      keyWork: "",
      storageName: "chainStore", // storage的key
      showHistory: false, // 显示历史搜索记录,
      searchHistoryList: "",
      pageReload: false, // 通过if刷新页面
      info: [],
      // 购物车
      store_id: "",
      carts:[],
      goodsCartsTotal:[],
      _goodsInfo:[],
      showGood:false,
      activeGood:[],
      themeColor:'',
      cartsNum:[],
      cartsTotal:[],

      isLoadMore: true,
      page: 1,
      total_page: 0
    };
  },
  components: { sarchHistory, yzGoodsPopup },
  activated() {
    if (this.$route.params.keyword) {
      this.keyWork = this.$route.params.keyword;
    }
    if (this.$route.params.store_id) {
      this.store_id = this.$route.params.store_id;
    }
    this.getData();
    this.getCart();
    this.themeColor = JSON.parse(localStorage.getItem("yz_basic_info")).theme_color || "";
  },
  methods: {
    goodsOrder(status){
      console.log('去结算',this.carts)
      let val = this.carts;
      let sum = 0;
      if (!status && !this.isHasDifferType(val)) {
        return;
      }

      this.carts.forEach(val => {
        sum += val.total;
      });

      if (sum == 0) {
        this.$toast("购物车暂无商品")
        return;
      }

      if (val.length == 0 || this.carts.length == 0) {
        return;
      } else {
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              store_id: this.store_id,
              tag: "store"
            }
          )
        );
      }
    },
    isHasDifferType(data) {
      //门店购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
      // 商品不是安装服务商品，直接没有live_install这个字段
      let open_state = 0; //有安装服务的商品
      let clone_state = 0; //没安装服务的商品
      let plugin_name = "";
      data.forEach(item => {
        if (item.live_install && item.live_install.open_state == 1) {
          open_state += 1;
          plugin_name = item.live_install.plugin_name;
        } else {
          clone_state += 1;
        }
      });
      if (open_state != 0 && clone_state != 0) {
        //都有值说明存在 两种 不同商品类型，提示框显示
        Dialog.confirm({
          title: "提示",
          message: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`
        })
          .then(() => {
            this.goodsOrder(data, true);
          })
          .catch(() => {});
        return false;
      }
      return true;
    },
    childGoodTap(id) {
      $http
        .post("goods.goods.get-goods-page", {
          id: Number(id)
        },"")
        .then(({ data, msg, result }) => {
          if (result == 0) {
            this.$toast(msg);
            return;
          }
          this._goodsInfo = data;
          this.activeGood = data.get_goods;
          this.showGood = true;
        });
    },
    yzGoodsPopupClose() {
      this.showGood = false;
      this.activeGood = {};
    },
    // 点击tag搜索
    serachTag(data) {
      this.keyWork = data;
      this.getData();
    },
    fateOutEnter() {
      this.getSosoHeight();
    },
    fateOutLeave() {
      this.getSosoHeight();
    },
    hidebox() {
      this.searchHistoryList = window.localStorage.getItem(this.storageName) ? JSON.parse(window.localStorage.getItem(this.storageName)) : [];
      if (this.searchHistoryList.length > 0) {
        this.showHistory = true;
      }
    },
    // 动态获取头部栏的高度
    getSosoHeight() {
      this.pageReload = !this.pageReload;
      this.$nextTick(() => {
        this.sosoH = this.$refs.soso.offsetHeight;
      });
    },
    searchBlur() {
      this.showHistory = false;
    },
    getData() {
      if (this.$refs.searchHistory && this.keyWork) {
        this.$refs.searchHistory.appendKeywords(this.keyWork);
        this.getSosoHeight();
      }
      $http.get("plugin.chain-store.frontend.controller.index.search-goods", { keyword: this.keyWork, store_id: this.$route.params.store_id }, "").then(
        response => {
          if (response.result === 1) {
            this.info = response.data.list.data;
            this.isLoadMore = true;
            this.total_page = response.data.list.last_page;
          } else {
            this.$toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        return;
      } else {
        this.page = this.page + 1;
        let json = { page: this.page, keyword: this.keyWork, store_id: this.$route.params.store_id };
        $http.get("plugin.chain-store.frontend.controller.index.search-goods", json, " ").then(
          response => {
            if (response.result === 1) {
              let myData = response.data.list.data;
              this.info = this.info.concat(myData);
              this.isLoadMore = true;
              this.total_page = response.data.list.last_page;
            } else {
              this.$toast(response.msg);
            }
          },
          function (response) {
            console.log(response);
          }
        );
      }
    },
    getCart(goods) {
      var that = this;
      $http
        .get("plugin.store-cashier.frontend.shoppingCart.member-cart.index", {
          store_id: this.store_id
        })
        .then(
          response => {
            if (response.result === 1) {
              that.carts = response.data;
              // this.info.member_cart.json = response.data;
              that.goodsCarts = [];
              that.cartsNum = 0;
              that.cartsTotal = 0;
              that.carts.forEach(item => {
                this.$set(that.goodsCarts, item.goods_id, item);
                // if (goods && goods.id == item.goods_id) {
                //   goods.buyNum = item.total;
                // }
                // // if (item.goods_id === that.goodsInfo.id && item.option_id === optionsId) {
                //   that.popNum = item.total;
                //   that.popCard = item;
                // }
                that.cartsNum += item.total;
                if(item.is_failure == 0){
                  that.cartsTotal += item.total * item.goods.price;
                }
              });
              that.goodsCartsTotal = that.calculateTotal(that.carts);
              that.cartsTotal = parseFloat(that.cartsTotal).toFixed(2);
            } else {
              //Toast("请输入提货人信息");
              //return;
            }
          },
          response => {
            //alert('网络错误，请稍后再试！')
          }
        )
        .catch(err => {
          console.log(err);
        });
    },
    //不同规格的同一商品求和
    calculateTotal(arr) {
      let newArr = []; // 保存求和后的购物车数量列表
      let temp = {};
      let newArr2 = [];
      for (let i in arr) {
        let key = arr[i].goods_id;
        if (temp[key]) {
          temp[key].total = temp[key].total + arr[i].total; //id相同则把数量相加
        } else {
          temp[key] = {};
          temp[key].goods_id = arr[i].goods_id;
          temp[key].total = arr[i].total;
        }
      }
      for (let k in temp) {
        newArr.push(temp[k]);
      }
      newArr.forEach(item => {
        this.$set(newArr2, item.goods_id, item);
      });
      return newArr2;
    }
  }
};
</script>
<style lang="scss" scoped>
.chainStoreSearch {
  background: #fff;
}
.searchInp {
  .van-search {
    padding: 0.5rem 0.75rem;
  }
}
.list {
  padding: 0.53rem 0.75rem;
  box-sizing: border-box;
  background: #fff;
  padding-bottom: 3rem;
  .lis {
    margin-bottom: 0.63rem;
    padding: 0.75rem;
    box-sizing: border-box;
    display: flex;
    .right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .title {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-align: left;
        font-weight: 500;
        color: #3b3b4a;
      }
      .price {
        font-size: 1rem;
        font-weight: 500;
        color: #f15353;
        text-align: left;
      }
    }
    .left {
      flex-shrink: 0;
      width: 4.38rem;
      height: 4.38rem;
      border-radius: 0.5rem;
      margin-right: 0.63rem;
      img {
        width: 100%;
        height: 100%;
        border-radius: 0.5rem;
      }
    }
  }
}
</style>
